/**

* <p>Title: OrderTest.java</p>

* <p>Description: </p>

* <p>Copyright: Copyright (c) 2021</p>

* <p>Company: www.chinasofti.com</p>

* @author knowno

* @date 2021年1月16日

* @version 1.0

*/
package com.etc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;

import com.etc.entity.Items;
import com.etc.util.DBUtil;

/**
 * 
 * <p>
 * Title: OrderTest
 * </p>
 * 
 * <p>
 * Description:
 * </p>
 * 
 * @author knowno
 * 
 * @date 2021年1月16日
 * 
 */
public class OrderTestBatch {

	public static void main(String[] args) throws SQLException {

		// 订单项(3项)
		Items oitem1 = new Items(0, 2, 1, "1002", 1000, 1, 1);
		Items oitem2 = new Items(0, 2, 2, "1002", 1000, 1, 1);
		Items oitem3 = new Items(0, 2, 3, "1002", 1000, 1, 1);
		List<Items> items = Arrays.asList(oitem1, oitem2, oitem3);

		Connection conn = DBUtil.getConn();

		// 设置事务边界(不再自动提交了)
		conn.setAutoCommit(false);

		// itemsid 自动增长
		String sql = "INSERT INTO `zmall`.`tbl_items`(`itemsid`, `count`, `goodsid`, `userid`, `shopid`, `orderid`, `cost`) VALUES (null, ?, ?, ?, ?, ?, ?)";

		// 创建一个preparedStatement
		PreparedStatement pstmt = conn.prepareStatement(sql);

		// 补齐参数

		// items
		for (Items it : items) {
			pstmt.setObject(1, it.getCount());
			pstmt.setObject(2, it.getGoodsid());
			pstmt.setObject(3, it.getUserid());
			pstmt.setObject(4, it.getShopid());
			pstmt.setObject(5, it.getOrderid());
			pstmt.setObject(6, it.getCost());

			// 添加到Statement对象的当前命令列表中
			pstmt.addBatch();

		}

		// 执行executeBatch作为批处理执行
		int[] result = pstmt.executeBatch();
		int total = 0;
		// 得到批处理的结果
		for (int i = 0; i < result.length; i++) {
			System.out.println(result[i]);
			total += result[i];
		}

		if (total == items.size()) {
			System.out.println("事务提交");
			conn.commit();
		} else {
			System.out.println("事务回滚");
			conn.rollback();
		}

	}

}
